# -*- coding: utf-8 -*-

from datetime import datetime,timedelta

class Message():
    def __init__(self,id,title,url,counterpart="",sector="",date="1970-01-01 00:00",content=""):
        self.id = id
        self.title = title
        self.url = url
        self.counterpart = counterpart
        self.sector =sector
        self.date = datetime.strptime(date[:16],"%Y-%m-%d %H:%M")
        self.content = content
    def __str__(self):
        return "%s-%s-%s" % (self.title,self.counterpart,self.date)
    def inOneDay(self):
        return self.date.day == datetime.now().day
    def inOneWeek(self):
        return self.date > datetime.now() - timedelta(days=7)
    def inOneMonth(self):
        return self.date > datetime.now() - timedelta(days=30)
    def all(self):
        return True



import sqlite3
class DBManager():
    def __init__(self,db):
        self.db = sqlite3.connect(db)
        self.query = self.db.cursor()
        self.__initTable()
        
    def __initTable(self):
        self.query.execute("create table if not exists msg (id TEXT primary key,date DATETIME,content TEXT)")
        self.db.commit()
    
    def addMessage(self,msg):
        try:
            self.query.execute("INSERT INTO msg VALUES ('%s','%s','%s')" % (msg.id,msg.date,msg.content))
            self.db.commit()
            return 1
        except:
            return 0
    def commitContent(self,msg):
        try:
            self.query.execute("UPDATE msg SET content='%s' where id=%s" % (msg.content,msg.id))
        except:
            pass
    def getMessage(self,id):
        self.query.execute("SELECT * FROM msg WHERE id=%s" % id)
        ret = self.query.fetchall()
        if len(ret)>0:
            return ret[0][2]
        else:
            return None


        